from MyTools.DBUtils import DBUtils


class UserDAO:
    def __init__(self):
        self.db = DBUtils(password='root', database='finance')

    def create_user(self, username, password, pay_pwd=None, real_name=None, reputation='良好'):
        sql_user = "INSERT INTO `user`(`username`,`password`,`paypwd`,`realname`,`reputation`) VALUES (%s, MD5(%s), %s, %s, %s)"
        sql_admin = "INSERT INTO `admin`(`username`, `password`) VALUES (%s, MD5(%s))"
        sql = sql_admin if username.find("admin") != -1 else sql_user
        self.db.update(sql, (username, password, pay_pwd, real_name, reputation))

    def delete_user(self, username):
        sql = "DELETE FROM `user` WHERE `username` = %s"
        self.db.update(sql, (username,))

    def get_user(self, username):
        sql_user = "SELECT * FROM `user` WHERE `username` = %s"
        sql_admin = "SELECT * FROM `admin` WHERE `username` = %s"
        sql = sql_admin if username.find("admin") != -1 else sql_user
        return self.db.select(sql, (username,))

    def clean_user(self):
        sql = "DELETE FROM `user`"
        self.db.update(sql)

    def pre_option(self, username, db_pwd, is_exist):
        # 执行前数据准备
        user = self.get_user(username)
        if is_exist == 1:
            if not user:
                self.create_user(username, db_pwd)
        elif is_exist == 0:
            if user:
                self.delete_user(username)
        else:
            print("Error!")
        return user


if __name__ == '__main__':
    print("admin".find("admin") != -1)
